/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */
package org.apache.myfaces.test.webapp.impl;

import net.sf.cglib.core.Signature;
import org.apache.myfaces.test.webapp.impl.metadata.assertion.AssertableELExpression;
import org.apache.myfaces.test.webapp.impl.metadata.assertion.AssertableProxyMethod;
import org.apache.myfaces.test.webapp.impl.metadata.assertion.AssertableValue;
import org.apache.myfaces.test.webapp.impl.metadata.assertion.TestAssertExpectCall;
import org.objectweb.asm.Type;

import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.el.MethodInfo;
import javax.faces.application.Application;
import javax.faces.component.UICommand;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Cosmin Martinconi, 12.08.2010
 */
public class ActionListenerWrapper implements ActionListener {

    private List<TestAssertExpectCall> expectCall;
    private Application application;

    public ActionListenerWrapper(Application application) {
        this.application = application;
        expectCall = new ArrayList<TestAssertExpectCall>();
    }

    public void processAction(ActionEvent actionEvent) throws AbortProcessingException {
        getWrapped().processAction(actionEvent);

        for (TestAssertExpectCall taec : expectCall) {
            if (validateCallExpected(actionEvent, taec.getAssertableValue()))
                taec.setCalled(true);
        }
    }

    private boolean validateCallExpected(ActionEvent actionEvent, AssertableValue assertableValue) {

        if ((assertableValue == null) || !(actionEvent.getSource() instanceof UICommand))
            return false;

        MethodExpression methExpr = ((UICommand) actionEvent.getSource()).getActionExpression();
        FacesContext fc = FacesContext.getCurrentInstance();

        if (assertableValue instanceof AssertableELExpression) {
            AssertableELExpression elValue = (AssertableELExpression)assertableValue;
            ExpressionFactory exprFactory = fc.getApplication().getExpressionFactory();
            MethodExpression valueExpr = exprFactory.createMethodExpression(fc.getELContext(), elValue.getElValue(), null, new Class<?>[]{});

            return methExpr.equals(valueExpr);
        }

        if (assertableValue instanceof AssertableProxyMethod) {
            AssertableProxyMethod methodValue = (AssertableProxyMethod)assertableValue;
            Signature sig = methodValue.getMethodProxy().getSignature();
            String beanName = AnnotationManager.getCurrentInstance().getBeanName(methodValue.getMethodObj().getClass().getSuperclass());

            MethodInfo methInfo = methExpr.getMethodInfo(fc.getELContext());

            return methExpr.getExpressionString().matches("#\\{" + beanName + "\\..*}") &&
                    methInfo.getName().equals(sig.getName()) &&
                    Type.getType(methInfo.getReturnType()).equals(sig.getReturnType());
        }

        return false;
    }


    private ActionListener getWrapped() {
        return application.getActionListener();
    }

    public void addExpectCall(TestAssertExpectCall eCall) {
        this.expectCall.add(eCall);
    }

    public void removeExpectCall(TestAssertExpectCall eCall) {
        expectCall.remove(eCall);
    }
}
